package cn.tedu.mall.seckill.timer;

import cn.tedu.mall.seckill.mapper.SeckillSpuMapper;
import cn.tedu.mall.seckill.utils.RedisBloomUtils;
import cn.tedu.mall.seckill.utils.SeckillCacheUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;
import java.time.LocalDateTime;

//将spuid的数组加载到布隆过滤器中
public class InitailBloomJob implements Job {
    @Autowired
    private RedisBloomUtils redisBloomUtils;
    @Autowired
    private SeckillSpuMapper seckillSpuMapper;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //首先我们获取秒杀批次的key
        //模拟多个秒杀批次，两次
        //两次秒杀之间都可以看到商品，避免两个批次之间的瞬间空档期，也允许用户看到下一个批次的商品
        String bloomTodayKey = SeckillCacheUtils.getBloomFilterKey(LocalDate.now());
        String bloomTomorrowKey = SeckillCacheUtils.getBloomFilterKey(LocalDate.now().plusDays(1));

        //获取spuId数组
        Long[] spuIds = seckillSpuMapper.selectAllSeckillSpuIds();
        //布隆过滤器中支持添加String类型的数组
        String[] strSpuIds = new String[spuIds.length];
        //遍历转换
        for (int i = 0; i < spuIds.length; i++) {
            strSpuIds[i]=spuIds[i]+"";
        }
        //将String[]存储到布隆过滤器中
        redisBloomUtils.bfmadd(bloomTodayKey,strSpuIds);
        redisBloomUtils.bfmadd(bloomTomorrowKey,strSpuIds);
        System.out.println("布隆过滤器加载完成");
    }
}
